package me.atbar.moonlib.storage.file;

import lombok.Getter;
import lombok.NonNull;
import me.atbar.moonlib.Main;
import me.atbar.moonlib.util.FileUtils;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.scheduler.BukkitRunnable;
import java.io.File;
import java.io.IOException;

/**
 * @author Administrator
 */
public class YamlConfig implements Config {

    @Getter
    private final File file;
    private final YamlConfiguration yaml;
    private long last;

    public YamlConfig(@NonNull String path) {
        this.file = FileUtils.getFileInstance(path);
        this.yaml = YamlConfiguration.loadConfiguration(file);
        this.last = FileUtils.getFileInstance(path).lastModified();
        create();
    }

    @Override
    public void create() {
        FileUtils.createFile(file.getPath());
    }

    @Override
    public void set(@NonNull String key, @NonNull Object value) {
        yaml.set(key, value);
        save();
    }

    @Override
    public void delete(@NonNull String key) {
        yaml.set(key, null);
        save();
    }

    @Override
    public void save() {
        try {
            yaml.save(file);
        } catch (IOException error) {
            error.getMessage();
        }
    }

    @Override
    public void autoSave(int loop) {
        new BukkitRunnable() {
            @Override
            public void run() {
                if(file.lastModified() != last) {
                    save();
                    updateLast();
                }
            }
        }.runTaskTimerAsynchronously(Main.getInstance(), 0L, loop * 20);
    }

    private void updateLast() {
        this.last = file.lastModified();
    }

}
